from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django import forms
from django.contrib.auth.models import User
from userprofile.models import userprofile
from django.core.context_processors import csrf
from django.contrib.auth import logout
from django.contrib.auth.views import password_change
from django.template import RequestContext

GENDER_CHOICES = (
	('', 'Decline'),
	('M', 'Male'),
	('F', 'Female'),
)

class NewUserForm(forms.Form):
	username = forms.CharField(label=(u'Username*'), required=True, max_length=30)
	email = forms.EmailField(label=(u'Email Address*'), required=True)
	first = forms.CharField(label=(u'First Name*'), required=True, max_length=30)
	last = forms.CharField(label=(u'Last Name*'), required=True, max_length=30)
	birthdate = forms.DateField(('%m/%d/%Y',), label='Birth Date (MM/DD/YY)', required=False,
		widget=forms.DateTimeInput(format='%m/%d/%Y')
	)
	gender = forms.CharField(label=(u'Gender'), required=False, max_length=1, widget=forms.Select(choices=GENDER_CHOICES))
	#address = forms.CharField(label=(u'Mailing Address'), required=False)
	phone = forms.CharField(label=(u'Phone Number'),required=False )
	password1 = forms.CharField(label=(u'Password*, must be at least 6 characters'), required=True ,widget=forms.PasswordInput(render_value=False))
	password2 = forms.CharField(label=(u'Confirm Password*'), required=True, widget=forms.PasswordInput(render_value=False))

	def check_for_errors(self):
		data = self.cleaned_data

		try:
			User.objects.get(username = data['username'])
		except User.DoesNotExist:
			pass
		else:
			return 'Error: account already exists with this username'

		try:
			User.objects.get(email = data['email'])
		except User.DoesNotExist:
			pass
		else:
			return 'Error: account already exists with this email address'

		if data["password1"] != data["password2"]:
			return 'Error: passwords do not match'

		return ''

	def save(self):
		data = self.cleaned_data
		user = User.objects.create_user(data['username'], data['email'], data['password1'])
		user.first_name = data['first']
		user.last_name = data['last']
		user.is_active = True
		user.save()

		profile = userprofile(user=user)
		profile.birthdate = data['birthdate']
		profile.gender = data['gender']
		#profile.address = data['address']
		profile.phone = data['phone']
		profile.save()

		return user

def register(request):
	message = ''
	if request.method == 'POST':
		form = NewUserForm(request.POST)
		if form.is_valid():
			message = form.check_for_errors()
			if len(message) == 0:
				new_user = form.save()
				return HttpResponseRedirect("/userprofile/")
	else:
		form = NewUserForm()
	return render_to_response("accounts/form.html", {'form': form, 'message':message, 'csrf_token':csrf(request)['csrf_token']}, context_instance=RequestContext(request))

def logoutView(request):
	logout(request)
	return HttpResponseRedirect("/")

def loginView(request):
	return HttpResponseRedirect("/")

